<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
use think\db\Where;
class GoodsSkulogic{

    /**
     * 添加
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function list($user_id, $store_id, $goods_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	            => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
           
            $map = [];
            if($goods_id > 0) $map['goods_id'] = $goods_id;
            $list = model('ErpGoodsSku') -> where($map) -> paginate();
            $rel_list =[];
            foreach ($list as $key => $value) {
                $lista = $this -> goods_sku_info_skuid($user_id, $value['id'], $store_id, $is_goodsinfo = 1);
                $rel_list[] = $lista['data'];
                
            }//dump($list);die;
            $result_list = [];
			$result_list['total']  			= $list -> total();//总数
            $result_list['current_page']	= $list -> currentPage();//页码
            $result_list['last_page']   	= $list -> lastPage();//总页数
            $result_list['per_page']   		= $list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            
           // dump($rel_list);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 商品sku list
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function goods_sku_list($user_id, $store_id, $goods_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	            => $user_id,
                'goods_id' 	            => $goods_id,
            ];
            /********行为参数赋值（*）********/
            //dump($goods_id);
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];
            if($goods_id > 0) $map['goods_id'] = $goods_id;
            $list = model('erp/ErpGoodsSku')->where($map) -> paginate();
            $list1 = model('erp/ErpGoodsSku')->where($map) -> select();
            foreach ($list1 as $key => $value) {
                $lista = $this -> goods_sku_info_skuid($user_id, $value['id'], $store_id, 0);//dump($lista);
                $rel_list[] = $lista['data'];
                
            }
            $result_list = [];
			$result_list['total']  			= $list -> total();//总数
            $result_list['current_page']	= $list -> currentPage();//页码
            $result_list['last_page']   	= $list -> lastPage();//总页数
            $result_list['per_page']   		= $list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;

           // dump($rel_list);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 单品详情
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function  goods_sku_info($user_id, $goods_id, $store_id, $specifications1_attribute_id, $specifications2_attribute_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	                                => $user_id,
                'goods_id' 	                                => $goods_id,
                'store_id' 	                                => $store_id,
                'specifications1_attribute_id' 	            => $specifications1_attribute_id,
                'specifications2_attribute_id' 	            => $specifications2_attribute_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/ 
            //单品详情
            $info = model('ErpGoodsSku') -> getSkuInfoByGss($goods_id, $specifications1_attribute_id, $specifications2_attribute_id);
            if($info['code'] != 200){
                DB::rollback();
                return array_out(-1005, 'error1');//后置错误 -1003
            }
            $sku_id = $info['data']['id'];

            $rel_info = $this -> goods_sku_info_skuid($user_id, $sku_id, $store_id);
            if($rel_info['code'] != 200){
                DB::rollback();
                return array_out(-1005, 'error2');//后置错误 -1003
            }

            $result = $rel_info['data'];

           // dump($rel_list);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 单品详情
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function  goods_sku_info_skuid($user_id, $sku_id, $store_id = 0, $is_goodsinfo = 1){
        DB::startTrans();//启动事务
        try{
            $info = model('erp/ErpGoodsSku') -> find($sku_id);
            if(!$info){
                DB::rollback();
                return array_out(-1005, 'sku error');//异常错误 -9999
            }
            
            $goods_id = $info->goods_id;
            $goods_info = [];
            if($is_goodsinfo){//dump($is_goodsinfo);
                //商品详情
                $goods_info_obj = controller('Goodslogic', 'logic') -> getGoodsInfo($goods_id, $store_id);//dump($goods_info_obj);
                if($goods_info_obj['code'] != 200 ){
                    DB::rollback();
                    return array_out(-1005, 'error2');//后置错误 -1003
                }
                $goods_info = $goods_info_obj['data'];
            }

            $info_f = [];
            $list = controller('erp/GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $sku_id);
            if($list['code'] == 200){
                $info_f['stock_num']        = (int)$list['data']['stock_num'];
                $info_f['frozen_num']       = (int)$list['data']['frozen_num'];
                $info_f['available_num']    = (int)$list['data']['available_num'];
                $info_f['price']            = (string)$list['data']['price'];
                $info_f['sku_status']       = (int)$list['data']['sku_status'];
            }else{
                $info_f['stock_num']        = (int)0;
                $info_f['frozen_num']       = (int)0;
                $info_f['available_num']    = (int)0;
                $info_f['price']            = (string)'无货';
                $info_f['sku_status']       = (int)1;
            }

            $rel_info = [
                'skuId'                             => $info->id,
                'goodsInfo'                         => $goods_info,
                'coverUrl'                          => 1,
                'goodsSpecifications'               => $info->goods_specifications,
                'specifications1_attribute_id'      => $info->specifications1_attribute_id,
                'specifications2_attribute_id'      => $info->specifications2_attribute_id,
                'price'                             => $info->price,
                'article_no'                        => (string)$info->article_no,
                'weight'                            => (string)$info->weight,
                'volume'                            => (string)$info->volume,   
                'skuStatus'                         => (int) $info_f['sku_status'],//门店自己有上下架的状态
                'code'                              => (string) $info->code,
                'kucunjiage'                        => (object) $info_f,

            ];
            
           
			DB::commit();
            return array_out(200, 'success', $rel_info);
        } catch (\Exception $e) {
			DB::rollback();dump($e -> getMessage());
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function from_to_sku_num($user_id, $from_warehouse_id, $to_warehouse_id, $sku_arr){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	            => $user_id,
                'from_warehouse_id' 	=> $from_warehouse_id,
                'to_warehouse_id' 	    => $to_warehouse_id,
                'sku_arr' 	            => $sku_arr,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            foreach ($sku_arr as $key => $value) {
                $skuinfo = $this -> goods_sku_info_skuid($user_id, $value, $store_id = 0);
                if($skuinfo['code'] != 200) continue;
                //$rel_list[$key]['skuInfo'] = $skuinfo['data'];
                $map = [];
                $map['warehouse_id'] = $from_warehouse_id;
                $map['sku_id'] = $value;
                $fromNum = (int) model('ErpGoodsWarehouseStockNum') -> where($map) -> value('available_num');
                $map = [];
                $map['warehouse_id'] = $to_warehouse_id;
                $map['sku_id'] = $value;
                $toNum = (int) model('ErpGoodsWarehouseStockNum') -> where($map) -> value('available_num');
                $rel_list[] = [
                    'skuInfo' => $skuinfo['data'],
                    'fromNum' => (int) $fromNum,
                    'toNum'   => (int) $toNum,
                ];
            }

            //dump($rel_list);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
}